/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.jcbp.builder.checkers;

import java.io.IOException;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipsejcde.core.CheckerStatus;
import org.eclipsejcde.core.IChecker;
import org.eclipsejcde.core.ICheckerStatus;
import org.eclipsejcde.jcbp.Activator;
import org.eclipsejcde.jcbp.JCBPCore;

/**
 * @author Amgad S Youssef
 * 
 */
public class SOSFrameworkChecker implements IChecker {

	@Override
	public ICheckerStatus[] check(IResource resource) throws CoreException {
		if (!(resource instanceof IProject)) {
			return new ICheckerStatus[] {};
		}
		IProject project = (IProject) resource;
		if (!project.hasNature(JCBPCore.NATURE_ID)) {
			return new ICheckerStatus[] {};
		}
		try {
			IJavaProject javaProject = JavaCore.create(project);
			IPackageFragment[] packageFragments = javaProject.getPackageFragments();
			for (int i = 0; i < packageFragments.length; i++) {
				if (packageFragments[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
					String dest = packageFragments[i].getResource().getLocation().toFile().toString();
					if (JCBPCore.sosFrameworkExists(dest)) {
						String parentPackageName = packageFragments[i].getElementName();
						if (parentPackageName == null || parentPackageName.equals("")) {
							JCBPCore.setProjectProperty(javaProject, JCBPCore.SOSFRAMEWORK_PACKAGE_NAME, "sosframework");
						} else {
							JCBPCore.setProjectProperty(javaProject, JCBPCore.SOSFRAMEWORK_PACKAGE_NAME, parentPackageName + ".sosframework");
						}
						return new ICheckerStatus[] {};
					}
				}
			}
			return new ICheckerStatus[] { new CheckerStatus(IMarker.SEVERITY_WARNING, "SOSFramework could not be found") };
		} catch (IOException e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.OK, e.getMessage(), e));
		}
	}
}
